package com.zkoko.thread;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by Administrator on 2018/5/26.
 */
public class SemaphoreDemo implements Runnable {
    //构造函数的参数限制了能够允许同时执行方法的个数
    final Semaphore semaphore = new Semaphore(5);

    @Override
    public void run() {
        try {
            semaphore.acquire();
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getId() + ":done!");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10) ;
        SemaphoreDemo semaphoreDemo = new SemaphoreDemo() ;

        for (int i = 0; i < 20; i++) {
            executorService.submit(semaphoreDemo) ;
        }

    }
}
